import React, { useEffect, useState } from 'react'
import { Layout, Menu } from 'antd';
import {
  SettingOutlined,
} from '@ant-design/icons';
import './sidemenu.css'
import { withRouter } from 'react-router-dom';
import axios from 'axios';
import { connect } from 'react-redux';
const { Sider } = Layout;
const { SubMenu } = Menu;



function ComponentName(props) {
  const {role:{rights}} =JSON.parse(localStorage.getItem("token"))
  const [menu,setMenu]=useState([])
  // 获取左侧菜单栏
  var getList= async ()=>{
    var res = await axios.get('/rights?_embed=children')
    setMenu(res.data)
  }
  // 根据级别字段判断是否渲染
  var checkPagePermission=(e)=>{
    return e.pagepermission && rights.includes(e.key)
  }
  useEffect(()=>{
    getList()
    console.log(props.location.pathname);
  },[])
  const renderMenu = (e) => {
    return e.map((item, index) => {
      if (item.children?.length>0 && checkPagePermission(item)){
        return <SubMenu key={item.key} title={item.title} icon={item.icon}
        // onClick={()=>{props.history.push(item.key)}}
        >
          {renderMenu(item.children)}
        </SubMenu> 
      }
      
      return checkPagePermission(item) && <Menu.Item key={item.key} icon={item.icon} onClick={()=>{props.history.push(item.key)}}>{item.title}</Menu.Item>

    })
  }
  const selectKeys=[props.location.pathname]
  const openKeys=['/'+props.location.pathname.split('/')[1]]
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsde}>
      <div style={{display:"flex",height:"100%",flexDirection:"column"}}>
        <div className="logo" >全球新闻发布</div>
        <div style={{flex:1,overflow:"auto"}}>
          <Menu theme="dark" mode="inline" selectedKeys={selectKeys}
          defaultOpenKeys={openKeys}
          >
            {renderMenu(menu)}
          </Menu>
        </div>
      </div>

    </Sider>
  )
}

const mapDispatchtoProps=({collapsedReducer:{isCollapsde}})=>{
	return {
		isCollapsde
	}
}
export default connect(mapDispatchtoProps)(withRouter(ComponentName)) 
